package com.chb.filter;

import com.alibaba.fastjson.JSON;
import com.chb.common.CommonConstants;
import com.chb.utils.UserInfoContext;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 暂未使用
 * @author CHB
 * @createTime 2022-8-24 13:33
 */
@Component
public class ZuulGlobalFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取请求的上下文类 注意是：com.netflix.zuul.context包下的
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.addZuulRequestHeader(CommonConstants.USER_INFO_HEADER_NAME, URLEncoder.encode(JSON.toJSONString(UserInfoContext.getUserInfo()), StandardCharsets.UTF_8));
        ctx.addZuulRequestHeader(CommonConstants.TRACE_ID, MDC.get(CommonConstants.TRACE_ID));
        return null;
    }
}
